package com.lianbang.pharmacy.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import cn.ubest.mvvmcore.base.BaseViewModel
import cn.ubest.mvvmcore.bean.ListWrapper
import cn.ubest.mvvmcore.bean.LoadingState
import cn.ubest.mvvmcore.bean.ResultWrapper
import cn.ubest.mvvmcore.bean.Wrapper
import cn.ubest.mvvmcore.http.exception.DataCodeException
import cn.ubest.mvvmcore.interfaces.RequestHandler1
import cn.ubest.mvvmcore.interfaces.RequestHandler1Impl
import cn.ubest.mvvmcore.interfaces.RequestHandler2
import cn.ubest.mvvmcore.interfaces.RequestHandler2Impl
import cn.ubest.mvvmcore.utils.ActivityManager
import cn.ubest.mvvmcore.utils.CoroutineUtils
import cn.ubest.mvvmcore.utils.LogUtils
import com.lianbang.pharmacy.bean.*
import com.lianbang.pharmacy.model.UserModel
import com.lianbang.pharmacy.module.main.MainActivity
import com.lianbang.pharmacy.module.main.StartActivity
import com.lianbang.pharmacy.module.user.LoginActivity
import com.lianbang.pharmacy.util.LoginUtils
import kotlinx.coroutines.*
import java.lang.Exception

/**
 * Created by maoqi on 2020/12/18.
 */
class UserVM : BaseViewModel<UserModel>() {

    fun login(account: String, pwd: String) {
        requestWithLife(object : RequestHandler1Impl<UserBean>(this) {
            override suspend fun request1(): UserBean {
                val loginBean = mModel.login("Mao123456", "Mao123456").resolveWrapper()
                LoginUtils.mToken = loginBean.token
                return mModel.getUser().resolveWrapper()
            }

            override fun onSuccess(t: UserBean) {
                LoginUtils.loginSucc(t)
                val topActivity = ActivityManager.getInstance().topActivity
                if (topActivity is LoginActivity) {
                    MainActivity.start(topActivity, MainActivity.TAB_HOME)
                    topActivity.finish()
                }
            }
        })
    }

    fun getUser() {
        requestWithLife(object : RequestHandler1Impl<UserBean>(this) {
            override suspend fun request1(): UserBean {
                return mModel.getUser().resolveWrapper()
            }

            override fun onSuccess(t: UserBean) {
                LoginUtils.loginSucc(t)
            }
        })
    }
}